package servlets;

import beans.Drivers;
import service.DriversService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/DriversServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50)   // 50MB
public class DriversServlet extends HttpServlet {
    private DriversService driversService = new DriversService();

    // 保存上传文件的目录
    private static final String UPLOAD_DIRECTORY = "driver_licenses";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 这里可以处理查看司机列表的请求
        // 重定向到司机列表页面
        String action = req.getParameter("action");
        System.out.println("DriversServlet received GET request, action=" + action);

//        resp.sendRedirect("Alldrivers_Informations.jsp");
        List allRecords;
        DriversService driverService = new DriversService();
        if ("search".equals(action)) {
            System.out.println("search");
            String driverId = req.getParameter("driverId");
            String driverName = req.getParameter("driverName");
            String phoneNumber = req.getParameter("phoneNumber");
            String gender = req.getParameter("gender");
            String status = req.getParameter("status");

            List<Drivers> driverList = driverService.searchDrivers(
                    driverId, driverName, phoneNumber, gender, status
            );
            req.setAttribute("driverList", driverList);
            req.getRequestDispatcher("/pirt/driversBig/Alldrivers_Informations.jsp").forward(req, resp);
        } else if ("all".equals(action)) {
            List<Drivers> driverList = driverService.getAllDrivers();
            req.setAttribute("driverList", driverList);
            req.getRequestDispatcher("/pirt/driversBig/Alldrivers_Informations.jsp").forward(req, resp);
        } else if ("all2".equals(action)) {
            req.getRequestDispatcher("/pirt/driversBig/My_Account.jsp").forward(req, resp);
        } else if ("all3".equals(action)) {
            req.getRequestDispatcher("/pirt/driversBig/System_Home.jsp").forward(req, resp);
        } else if ("edit".equals(action)) {
            String driverIdStr = req.getParameter("driverId");
            if (driverIdStr != null && !driverIdStr.isEmpty()) {
                int driverId = Integer.parseInt(driverIdStr);
                Drivers driver = driverService.getDriverById(driverId);
                req.setAttribute("driver", driver);
            }
            req.getRequestDispatcher("/pirt/driversBig/edit_drivers.jsp").forward(req, resp);
        } else if ("add".equals(action)) {
            req.getRequestDispatcher("/pirt/driversBig/addDriver.jsp").forward(req, resp);
        } else if ("delete".equals(action)) {
            this.deleteVehicle(req,resp);
        }else if("123".equals(action))
        {
            req.getRequestDispatcher("/shouye.jsp").forward(req, resp);
        }else if("1234".equals(action))
        {
            req.getRequestDispatcher("/pirt/drivers/System_Home.jsp").forward(req, resp);
        }else if("a".equals(action))
        {
            // 刷新个人信息
             String refresh = req.getParameter("refresh");
             if ("true".equals(refresh)) {
                 HttpSession session = req.getSession();
                 Drivers currentDriver = (Drivers) session.getAttribute("user");
                 if (currentDriver != null) {
                     Drivers refreshedDriver = driversService.getDriverById(currentDriver.getDriverId());
                     if (refreshedDriver != null) {
                         session.setAttribute("user", refreshedDriver);
                         // 移除refresh参数，避免无限刷新
                         resp.sendRedirect(req.getContextPath() + "/DriversServlet?action=a");
                         return;
                     }
                 }
             }
            req.getRequestDispatcher("/pirt/drivers/My_Account.jsp").forward(req, resp);
        }else if("b".equals(action))
        {
            req.getRequestDispatcher("/pirt/drivers/System_Home.jsp").forward(req, resp);
        }else if("c".equals(action))
        {
            req.getRequestDispatcher("/pirt/drivers/All_Order.jsp").forward(req, resp);
        }else if("d".equals(action))
        {
            req.getRequestDispatcher("/pirt/drivers/Repair_Orders.jsp").forward(req, resp);
        }else if("e".equals(action))
        {
            req.getRequestDispatcher("/pirt/drivers/Claim_expenses.jsp").forward(req, resp);
        } else {
             // 未知的 GET action
             resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "未知操作");
        }
    }

    //修改司机信息
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ParseException {
        System.out.println("edit_servlet");
        Drivers driver = new Drivers();
        try {
            // 封装参数
            driver.setDriverId(Integer.parseInt(req.getParameter("driverId")));
            driver.setDriverName(req.getParameter("driverName"));
            driver.setPhoneNumber(req.getParameter("phoneNumber"));
            driver.setEmail(req.getParameter("email"));
            driver.setGender(req.getParameter("gender"));
            driver.setDriverLicenseNumber(req.getParameter("driverLicenseNumber"));
            driver.setRemarks(req.getParameter("remarks"));
            String expirationDateStr = req.getParameter("driverLicenseExpirationDate");
            if (expirationDateStr != null && !expirationDateStr.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date expirationDate = sdf.parse(expirationDateStr);
                driver.setDriverLicenseExpirationDate(expirationDate);
            }

            Part imagePart = req.getPart("driverLicenseImage");
            driver.setStatus(req.getParameter("status"));

            try {
                driversService.updateDriver(driver);
                resp.sendRedirect(req.getContextPath() + "/DriversServlet?action=all");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }catch (NumberFormatException e) {

            req.getRequestDispatcher("/addDriver.jsp").forward(req, resp);
        }
    }

    private void deleteVehicle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            int driverId = Integer.parseInt(req.getParameter("driverId"));
            String name=req.getParameter("name");
            boolean success = driversService.deleteDriver(driverId);
            System.out.println(success);
            if (success) {
                req.getSession().setAttribute("message", name+"删除成功！");
            } else {
                req.getSession().setAttribute("error", "车辆不存在或删除失败！");
            }
            resp.sendRedirect(req.getContextPath() + "/DriversServlet?action=all");
        } catch (NumberFormatException e) {
            System.out.println("error");
            req.setAttribute("error", "无效的车辆ID");
             try {
                 req.getRequestDispatcher("/pirt/driversBig/Alldrivers_Informations.jsp").forward(req, resp);
             } catch (ServletException ex) {
                 throw new RuntimeException(ex);
             } // 转发到司机列表页面显示错误
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
         System.out.println("DriversServlet received POST request, action=" + action);

        if ("driver".equals(action)) {
            try {
                try {
                    this.add(request, response);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            } catch (SQLException var11) {
                throw new RuntimeException(var11);

            }
        }else if ("edit1".equals(action)) {
            try {
                this.update(request,response);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } else if ("changePassword".equals(action)) { // 添加处理修改密码的action
            handleChangePassword(request, response);
        }
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException, SQLException {
        Drivers driver = new Drivers();
        try {
            System.out.println("11111111add");
            // 封装参数
            driver.setDriverId(Integer.parseInt(request.getParameter("driverId")));
            driver.setDriverName(request.getParameter("driverName"));
            driver.setPhoneNumber(request.getParameter("phoneNumber"));
            driver.setEmail(request.getParameter("email"));
            driver.setGender(request.getParameter("gender"));
            driver.setDriverLicenseNumber(request.getParameter("driverLicenseNumber"));
            driver.setRemarks(request.getParameter("remarks"));
            // 设置密码
            String password = request.getParameter("password");
            if (password == null || password.trim().isEmpty()) {
                throw new IllegalArgumentException("密码不能为空");
            }
            driver.setPassword(password);
            
            String expirationDateStr = request.getParameter("driverLicenseExpirationDate");
            if (expirationDateStr != null && !expirationDateStr.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date expirationDate = sdf.parse(expirationDateStr);
                driver.setDriverLicenseExpirationDate(expirationDate);
            }

            Part imagePart = request.getPart("driverLicenseImage");

            // 调用Service
            DriversService service = new DriversService();
            boolean success = service.addDriver(driver, imagePart);

            if (success) {
                // 修复1：添加上下文路径 + return
                response.sendRedirect(request.getContextPath() + "/pirt/driversBig/addDriver.jsp?success=true");
            } else {
                response.sendRedirect(request.getContextPath() + "/pirt/driversBig/addDriver.jsp?success=error");
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "司机ID必须是数字");
            request.getRequestDispatcher("/addDriver.jsp").forward(request, response);
        } catch (IllegalArgumentException e) {
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("/addDriver.jsp").forward(request, response);
        } catch (Exception e) {
            request.setAttribute("error", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("/addDriver.jsp").forward(request, response);
        }
    }

    // 新增方法：处理修改密码请求
    private void handleChangePassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null || !(session.getAttribute("user") instanceof Drivers)) {
            response.sendRedirect(request.getContextPath() + "/login.jsp"); // 用户未登录或不是司机，重定向到登录页面
            return;
        }

        Drivers currentDriver = (Drivers) session.getAttribute("user");
        int driverId = currentDriver.getDriverId();

        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");

        // 基本验证
        if (oldPassword == null || oldPassword.trim().isEmpty() ||
            newPassword == null || newPassword.trim().isEmpty() ||
            confirmPassword == null || confirmPassword.trim().isEmpty()) {
            request.setAttribute("error", "所有密码字段都不能为空");
            request.getRequestDispatcher("/pirt/drivers/My_Account.jsp").forward(request, response);
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的新密码不一致");
            request.getRequestDispatcher("/pirt/drivers/My_Account.jsp").forward(request, response);
            return;
        }

        try {
            // 调用Service层方法修改密码
            boolean success = driversService.changePassword(driverId, oldPassword, newPassword);

            if (success) {
                // 密码修改成功
                request.setAttribute("message", "密码修改成功");
                // 强制用户重新登录
                 session.invalidate();
                 response.sendRedirect(request.getContextPath() + "/login.jsp?message=" + URLEncoder.encode("密码修改成功，请重新登录", "UTF-8"));

            } else {
                // 密码修改失败（例如原密码错误）
                request.setAttribute("error", "原密码不正确或修改失败");
                request.getRequestDispatcher("/pirt/drivers/My_Account.jsp").forward(request, response);
            }

        } catch (Exception e) {
            System.out.println("处理司机修改密码请求时出错: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("error", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("/pirt/drivers/My_Account.jsp").forward(request, response);
        }
    }
}